package com.accompany.fragment.order;


import static android.content.Context.MODE_PRIVATE;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.accompany.R;
import com.accompany.adapter.BaseRecyclerHolder;
import com.accompany.adapter.BaseRecyclerRefreshAdapter;
import com.accompany.api.bean.OrderMesgBean;
import com.accompany.api.category.OrderCategory;
import com.accompany.api.presenter.OrderPresenter;
import com.accompany.base.BaseBean;
import com.accompany.base.BaseFragment;
import com.accompany.dialog.LoginOutDialog;
import com.accompany.dialog.RoundCornerDialog;
import com.accompany.fragment.login.UserLoginActivity;
import com.accompany.fragment.order.activity.MineCommentsActivity;
import com.accompany.fragment.order.activity.OrderDetialsActivity;
import com.accompany.listener.OnQuiteDialogClickListener;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.main.MainActivity;
import com.accompany.refresh.RefreshLoadMoreRecycleAdapter;
import com.accompany.utils.HttpNetworkConnectUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ToastUtil;
import com.accompany.view.RecyclerViewLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 信息说明: 已完成
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/15 16 ：12
 * 项目名称：yuanban
 */
public class CompleteFragment extends BaseFragment implements OrderCategory.View, OnRefreshListener, OnLoadMoreListener {
    @BindView(R.id.base_refresh_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.base_refresh)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.relat_empty)
    RelativeLayout mEmptyLayout;
    private OrderPresenter mPresenter;
    private List<OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList> mlist = new ArrayList<>();
    private long mUserId;

    private int pageNumber = 1;
    private boolean isLoading =false;
    private BaseRecyclerRefreshAdapter<OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList> mAdapter;

    private LoginOutDialog dialog ;

    String mToken;
    private OrderMesgBean baseBean;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            smartRefreshLayout.autoRefresh();
        }
    }




    @Override
    public int getLayoutResource() {
        return R.layout.base_refresh_recycler_view;
    }

    @Override
    public void initLayoutView() {
        RecyclerViewLayoutManager.setLinearVerticalManager(getActivity(), mRecyclerView);
        mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        mPresenter = new OrderPresenter(this);
        SetPersenter(mPresenter);
        mAdapter = new BaseRecyclerRefreshAdapter<OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList>(getActivity(), mlist, R.layout.obl_item_view) {
            @Override
            public void convert(BaseRecyclerHolder holder, OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList item, int position, boolean isScrolling) throws IOException {
                holder.setText(R.id.obl_title, "订单号 : " + item.getOrderNo());
                holder.setText(R.id.ordre_price, "￥ " + item.getFinalPrice());
                holder.setText(R.id.fuw_xiagnm, item.getTitle());
                holder.setText(R.id.name, item.getOrderDTO().getPatientName());
                holder.setText(R.id.order_fuwtime, item.getOrderDTO().getPeriodStr());
                holder.setText(R.id.service_yiyuan, item.getOrderDTO().getHospitalName());
                holder.setText(R.id.orer_msg, item.getOrderDTO().getRemark());
                holder.setText(R.id.order_age, item.getOrderDTO().getPatientAge());
                TextView gender = holder.getView(R.id.order_gender);
                if (item.getOrderDTO().getPatientSex().equals("0")) {
                    gender.setText("女");
                } else if (item.getOrderDTO().getPatientSex().equals("1")) {
                    gender.setText("男");
                }
                TextView mOblMsg = (TextView) holder.getView(R.id.obl_msg);
                TextView my_dianpin = (TextView) holder.getView(R.id.my_dianpin);
                my_dianpin.setText("删除订单");
                my_dianpin.setVisibility(View.GONE);
                mOblMsg.setText("已完成");
                mOblMsg.setTextColor(Color.parseColor("#333333"));
                TextView mTobeServed = holder.getView(R.id.toserved_msg);
                mTobeServed.setText("查看评价");
                holder.getView(R.id.my_dianpin).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RoundCornerDialog dialog = new RoundCornerDialog(getActivity(), "确定要删除吗？", "确定", "取消", new OnQuiteDialogClickListener() {
                            @Override
                            public void onConfirm(Dialog dialog) {
                                mPresenter.getDeleteOrder(mToken, mlist.get(position).getId());
                                mlist.remove(position);
                                mAdapter.notifyItemRemoved(position);
                                mAdapter.notifyItemChanged(0, mlist.size());
                                dialog.dismiss();
                            }

                            @Override
                            public void onCancel(Dialog dialog) {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }
                });
                holder.getView(R.id.toserved_msg).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("orderId",String.valueOf(mlist.get(position).getId()));
                        bundle.putLong("acdId",mUserId);
                        openActivityWitchAnimation(MineCommentsActivity.class,bundle);
                    }
                });
            }
        };
        mAdapter.setDatas(mlist);
        mRecyclerView.setAdapter(mAdapter);
        if (!HttpNetworkConnectUtils.isNetworkConnected(getActivity())) {
            ToastUtil.showToastERROR(getActivity(), "网络不给力,请稍后重试");
        } else {
            mPresenter.getOrderList(pageNumber, mToken,mUserId,4);
        }
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);

    }

    @Override
    public void getOrderList(OrderMesgBean baseBean) {
        this.baseBean = baseBean;
        if (baseBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (baseBean.getData() != null && baseBean.getData().getList().size() > 0 ) {
                if (pageNumber == 1) {//第一次请求
                    if (isLoading) {//isLoading == true,上拉
                        isLoading = false;
                    } else {//刷新
                        mlist.clear();
                    }
                    mlist.addAll(baseBean.getData().getList());
                    mAdapter.setDatas(baseBean.getData().getList());
                    smartRefreshLayout.setEnableLoadMore(true);
                } else {// 上拉
                    if (baseBean.getData().isHasNextPage()) {
                        mlist.addAll(mlist.size(), baseBean.getData().getList());
                        mAdapter.add(baseBean.getData().getList());
                        smartRefreshLayout.setEnableLoadMore(true);
                    } else {
                        smartRefreshLayout.finishLoadMoreWithNoMoreData();
//                        ToastUtil.showToastINFO(getActivity(), "没有更多数据");
                    }

                }
                mEmptyLayout.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
            } else {
                if (isLoading) {
                    isLoading = false;
                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                }
            }
        } else if (baseBean.getCode() == ConstantStaticUrl.NO_LOGIN_CODE) {//未登录
            dialog = LoginOutDialog.getLoginOutDialog(getActivity());
            dialog.show();
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    dialog = null;
                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(getActivity());
                    getActivity().finish();
                    dialog.dismiss();
                    dialog = null;
                }
            });

        } else {//服务器返回错误信息
            ToastUtil.showToastINFO(getActivity(), baseBean.getMsg());
        }
    }

    @Override
    public void getDeleteOrder(BaseBean baseBean) {
        if (baseBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            ToastUtil.showToastSUCCESS(getActivity(), "订单删除成功");
        } else {
            ToastUtil.showToastINFO(getActivity(), baseBean.getMsg());
        }
    }

    @Override
    public void SetPersenter(Object persenter) {
    }

    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(getActivity(),mErrorMsg);
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (baseBean.getData().isHasNextPage()) {
            isLoading = true;
            pageNumber++ ;
            mPresenter.getOrderList(pageNumber, mToken, mUserId, 5);
        }else {
            isLoading = false;
        }
        smartRefreshLayout.finishLoadMore(500);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        mPresenter.getOrderList(pageNumber, mToken, mUserId, 5);
        smartRefreshLayout.finishRefresh(500);
    }

    @Override
    public void onResume() {
        super.onResume();
//        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
//        boolean isLogin = sharedPreferences.getBoolean("isLogin",false);
//        if (isLogin){
            smartRefreshLayout.autoRefresh();
//        }else {
//            mEmptyLayout.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.GONE);
//        }
    }
}
